﻿using System.Reflection;
using Newtonsoft.Json;
using SqlSugar;

namespace Aurora.AI.SqlSugar.Framework
{
    /// <summary>
    /// sql sugar db context
    /// </summary>
    public class SqlSugarDbContext
    {
        public readonly SqlSugarScope Scope;

        public SqlSugarDbContext(string connection, Assembly assembly, Action<SqlSugarScope>? action = default)
        {
            var mappingTypes = assembly.GetMappingTypes();

            SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = connection,
                DbType = DbType.MySql,
                InitKeyType = InitKeyType.Attribute, //从特性读取主键和自增列信息
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    //注意:  这儿AOP设置不能少
                    EntityService = (c, p) =>
                    {
                        /***高版C#写法***/
                        //支持string?和string  
                        if (p.IsPrimarykey == false && new NullabilityInfoContext()
                                .Create(c).WriteState is NullabilityState.Nullable)
                        {
                            p.IsNullable = true;
                        }

                        // 执行mapping
                        if (mappingTypes.Count > 0)
                            p.EntityServiceMapping(mappingTypes);
                    },
                    EntityNameService = (type, entity) =>
                    {
                        if (mappingTypes.Count > 0)
                            entity.EntityNameServiceMapping(type, mappingTypes);
                    }
                }
            }, db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")?.ToString() == "Development")
                    {
                        Console.WriteLine(sql + "\r\n" +
                                          JsonConvert.SerializeObject(pars.ToDictionary(it => it.ParameterName,
                                              it => it.Value)));
                        Console.WriteLine();
                    }
                };
            });
            Scope = sqlSugar;
            // init tables
            if (mappingTypes.Count > 0)
                Scope.InitTables(mappingTypes);
            if (action != null)
            {
                action(Scope);
            }
        }
    }
}